<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Storage;
use App\Repositories\FileRepo;
class FileController extends Controller
{
    private $host = '';
    private $port = '';
    public function __construct(Request $request)
    {
        $this->host = $request->getScheme().'://'.$request->getHost();
        if($request->getPort != 80){
            $this->port = ':'.$request->getPort();
        }

        // var_dump($request->getHost());
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function upload(Request $request)
    {
        $file = $request->file('file');

        if(!$file)  return  json_encode(['code'=>5000,'message'=>'文件不存在']);
        $originalName = $file->getClientOriginalName();

        $fileRepo = new FileRepo;

        if($path = $fileRepo->exits($originalName)) {
            return ['errno'=>0,'data'=>['url'=>$this->host.$this->port.$path]];
        }

        $path = $request->file('file')->store('images'.date('/Y/m/d',time()));
        $path = '/storage/'.$path;
        if(file_exists('.'.$path)) {
                $fileRepo->rsycSave($path,$originalName);
                return ['errno'=>0,'data'=>['ful_url'=>$this->host.$this->port.$path,'url'=>$path]];
        } else{
             return json_encode(['code'=>5000,'message'=>'文件保存失败'.$path]);
        }
    }
}
